from django.db.models import Q
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
from django.contrib.auth.hashers import make_password

from .serializers import *
from users.serializers import *
from .models import *
from users.models import *
from users.utils import redis_conn

import json


# 商家视图
class ShopsView(ViewSet):
    # 入驻申请
    def user_register(self,request):
        try:
            nickname = request.data.get("nickname")
            password = request.data.get("password")
            mobile = request.data.get("mobile")
            sms_code = request.data.get("sms_code")
            address = request.data.get("address")


            if not all([nickname,password,mobile,sms_code,address]):
                return Response({"errcode": 2, "msg": "提交信息不完整！"})

            user = ShopsModel.objects.filter(nickname=nickname,is_delete=False).first()
            if user:
                return Response({"errcode": 3, "msg": "名称已存在！"})

            user = UserModel.objects.filter(mobile=mobile,is_delete=False).first()
            if user:
                return Response({"errcode": 1, "msg": "手机号已注册！"})

            user = ShopsModel.objects.filter(mobile=mobile, is_delete=False).first()
            if user:
                return Response({"errcode": 1, "msg": "手机号已注册！"})

            code = redis_conn().get("sms_%s"%mobile)
            if not code:
                return Response({"errcode": 4, "msg": "验证码已过期！"})
            code = code.decode()
            if sms_code.lower() != code.lower():
                return Response({"errcode": 5, "msg": "验证码错误！"})

            hash_pwd = make_password(password)
            ShopsModel.objects.create(nickname=nickname, password=hash_pwd, mobile=mobile, address=address)
            return Response({"errcode":0,"msg":"注册成功！"})
        except Exception as e:
            print("错误",e)
            return Response({'errcode': 4, 'msg': '服务器错误'})

    # 获取单个商家用户信息
    def shops_dict(self, request):
        try:
            user_id = request.query_params.get('user_id')
            user_type = request.query_params.get("user_type")

            # print(user_id,type(user_id))
            # print(user_type,type(user_type))

            user = ShopsModel.objects.filter(id=user_id, is_delete=False).first()
            if not user:
                return Response({"errcode": 1, "msg": "用户不存在！"})
            if int(user_type) != 2:
                return Response({"errcode": 2, "msg": "非法请求！"})

            ser = ShopsSer(user)
            return Response({"errcode": 0, "msg": "ok！","data":ser.data})
        except Exception as e:
            print("错误", e)
            return Response({'errcode': 3, 'msg': '服务器错误'})

    # 获取所有商家信息
    def shops(self,request):

        try:
            user_id = request.query_params.get('user_id')

            user = ShopsModel.objects.all()

            ser = ShopsSer(user, many=True)
            return Response({'errcode':0,'msg':'获取成功','data':ser.data})
        except Exception as e:
            print("错误", e)
            return Response({'errcode':2,'msg':'服务器错误'})

    # 修改用户信息
    def up_user(self, request):
        try:
            user_id = request.data.get('user_id')

            nickname = request.data.get("nickname")
            avatar_url = request.data.get("avatar_url")
            intro = request.data.get("intro")
            address = request.data.get("address")
            password = request.data.get("password")
            work_time = request.data.get("work_time")
            start_price = request.data.get("start_price")

            print(user_id,type(user_id))

            flag = ShopsModel.objects.filter(nickname=nickname, is_apply=True, is_delete=False).exclude(id=user_id).count()
            if flag != 0:
                return Response({"errcode": 1, "msg": "该用户名已存在！"})

            user = ShopsModel.objects.filter(id=user_id, is_apply=True, is_delete=False)
            if not user:
                return Response({'errcode': 2, 'msg': '用户不存在！'})
            if nickname:
                user.update(nickname=nickname)
            if avatar_url:
                user.update(avatar_url=avatar_url)
            if intro:
                user.update(intro=intro)
            if address:
                user.update(address=address)
            if password:
                pwd = make_password(password)
                user.update(password=pwd)
            if work_time:
                user.update(work_time=work_time)
            if start_price:
                user.update(start_price=start_price)
            return Response({
                'errcode': 0,
                'msg': '修改成功！',
            })
        except Exception as e:
            print("错误", e)
            return Response({'errcode': 3, 'msg': '服务器错误'})

    # 获取单个商家详情
    def shops_desc(self, request, pk):
        try:
            user = ShopsModel.objects.filter(id=pk, is_delete=False).first()
            shops_ser = ShopsSer(user)

            return Response({"errcode": 0, "msg": "ok！", "data": shops_ser.data})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})


# 菜品类别
class GoodsTypeView(ViewSet):
    # 获取
    def list(self, request):
        try:
            user_id = request.query_params.get('user_id')

            goods_type = GoodsTypeModel.objects.filter(shops_id=user_id, is_delete=False).all()
            ser = GoodTypeSer(goods_type, many=True)
            return Response({"errcode": 0, "msg": "ok！", "data": ser.data})
        except Exception as e:
            print("错误", e)

    # 添加类别
    def add(self, request):
        try:
            user_id = request.data.get('user_id')

            name = request.data.get("name")

            goods_type_data = {
                "name": name,
                "shops": user_id,
            }
            # print("数据",goods_type_data)
            serializer = GoodTypeSer(data=goods_type_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response({"errcode": 0, "msg": "添加成功！"})
        except Exception as e:
            print("错误", e)

    # 修改类别
    def update(self, request):
        try:
            user_id = request.data.get("user_id")

            id = request.data.get("id")
            name = request.data.get("name")

            goods_type = GoodsTypeModel.objects.filter(id=id, shops_id=user_id, is_delete=False).first()
            if not goods_type:
                return Response({"errcode": 1, "msg": "类别不存在！"})

            goods_type_data = {
                "id": id,
                "name": name,
                "shops": user_id,
            }
            serializer = GoodTypeSer(instance=goods_type, data=goods_type_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response({"errcode": 0, "msg": "修改成功！"})
        except Exception as e:
            print("错误", e)

    # 删除类别
    def delete(self, request, pk):
        try:
            user_id = request.query_params.get("user_id")

            goods_type = GoodsTypeModel.objects.filter(id=pk, shops_id=user_id, is_delete=False)
            if not goods_type:
                return Response({"errcode": 1, "msg": "类别不存在！"})

            goods_type.update(is_delete=True)

            return Response({"errcode": 0, "msg": "删除成功！"})
        except Exception as e:
            print("错误", e)


# 菜品
class GoodsView(ViewSet):
    # 获取
    def list(self, request):
        try:

            user_id = request.query_params.get("user_id")

            # goods_type = GoodsTypeModel.objects.filter(Q(shops_id=user_id) |  Q(is_delete=False)).all()
            goods_type = GoodsTypeModel.objects.filter(shops_id=user_id, is_delete=False).all()

            temp = []
            for i in goods_type:
                goods = i.goodsmodel_set.filter(is_delete=False)
                temp += goods

            ser = GoodSer(temp, many=True)
            return Response({"errcode": 0, "msg": "ok！", "data": ser.data})
        except Exception as e:
            print("错误", e)

    # 添加菜品
    def add(self, request):
        try:
            user_id = request.data.get("user_id")

            name = request.data.get("name")
            price = request.data.get("price")
            image = request.data.get("image")
            type = request.data.get("type")


            goods_data = {
                "name": name,
                "price": price,
                "image": image,
                "type": type,
            }
            serializer = GoodSer(data=goods_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response({"errcode": 0, "msg": "添加成功！"})
        except Exception as e:
            print("错误", e)

    # 修改菜品
    def update(self, request):
        try:
            user_id = request.query_params.get("user_id")

            id = request.data.get("id")
            name = request.data.get("name")
            price = request.data.get("price")
            image = request.data.get("image")
            type = request.data.get("type")

            goods = GoodsModel.objects.filter(id=id, is_delete=False).first()
            if not goods:
                return Response({"errcode": 1, "msg": "商品不存在！"})

            goods_data = {
                "id": id,
                "name": name,
                "price": price,
                "image": image,
                "type": type,
            }
            serializer = GoodSer(instance=goods, data=goods_data)
            serializer.is_valid(raise_exception=True)
            serializer.save()

            return Response({"errcode": 0, "msg": "修改成功！"})
        except Exception as e:
            print("错误", e)

    # 删除菜品
    def delete(self, request, pk):
        try:
            user_id = request.query_params.get("user_id")

            goods = GoodsModel.objects.filter(id=pk, is_delete=False)
            if not goods:
                return Response({"errcode": 1, "msg": "商品不存在！"})

            goods.update(is_delete=True)

            return Response({"errcode": 0, "msg": "删除成功！"})
        except Exception as e:
            print("错误", e)


# 商家订单
class OrderViewSet(ViewSet):
    # 获取商家所有订单
    def get_order(self, request):
        try:
            user_id = request.query_params.get('user_id')

            order_list = OrderModel.objects.filter(shops_id=user_id,is_delete=False).all()
            ser = OrderSer(order_list,many=True)
            order_list = ser.data
            order_list = json.loads(json.dumps(order_list))
            for i in order_list:
                i["is_comment"] = False
                comment = CommentModel.objects.filter(order_id=i["id"],is_delete=False)
                if comment:
                    i["is_comment"] = True
            return Response({"errcode": 0, "msg": "ok！","data": order_list})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})

    # 获取未支付的订单
    def check_order(self, request):
        try:
            # user_id = request.query_params.get('user_id')
            user_id = request.data.get('user_id')

            order_list = OrderModel.objects.filter(shops_id=user_id,pay_state=1,is_delete=False).all()
            ser = OrderSer(order_list,many=True)

            order_list = ser.data
            order_list = json.loads(json.dumps(order_list))
            return Response({"errcode": 0, "msg": "ok！","data": order_list})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})

    # 获取已支付的订单
    def order_check(self, request):
        try:
            user_id = request.query_params.get('user_id')

            order_list = OrderModel.objects.filter(shops_id=user_id,pay_state=2,is_delete=False).all()
            ser = OrderSer(order_list,many=True)
            order_list = ser.data
            order_list = json.loads(json.dumps(order_list))
            return Response({"errcode": 0, "msg": "ok！","data": order_list})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})

    # 获取订单详情
    def order_desc(self, request, pk):
        try:
            user_id = request.query_params.get('user_id')
            # user_id = request.data.get('user_id')
            print(user_id)

            order = OrderModel.objects.filter(id=pk, shops_id=user_id, is_delete=False).first()
            print('order', order)
            order_goods_list = order.ordergoodsmodel_set.all()

            print('--------',order_goods_list)

            goods_list = []
            for i in order_goods_list:
                goods = i.goods
                goods_ser = GoodSer(goods)
                goods = json.loads(json.dumps(goods_ser.data))
                order_goods = OrderGoodsSer(i)
                order_goods = json.loads(json.dumps(order_goods.data))
                goods["order"] = order_goods
                goods_list.append(goods)
            order_ser = OrderSer(order)
            order = order_ser.data
            return Response({"errcode": 0, "msg": "ok！", "order": order, "goods_list": goods_list})
        except Exception as e:
            print("错误", e)
            return Response({"errcode": 1, "msg": "服务器错误！"})

